package yanyan.com.tochar;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.graphics.RectF;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.Spinner;
import android.widget.TextView;

import com.github.sumimakito.awesomeqr.AwesomeQrRenderer;
import com.github.sumimakito.awesomeqr.RenderResult;
import com.github.sumimakito.awesomeqr.option.RenderOption;
import com.github.sumimakito.awesomeqr.option.background.GifBackground;
import com.github.sumimakito.awesomeqr.option.background.StillBackground;
import com.github.sumimakito.awesomeqr.option.color.Color;
import com.github.sumimakito.awesomeqr.option.logo.Logo;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.hjq.permissions.Permission;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.entity.LocalMedia;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import pl.droidsonroids.gif.GifDrawable;
import yanyan.com.tochar.beans.AppInfo;
import yanyan.com.tochar.beans.QrCodeBean;
import yanyan.com.tochar.utils.CoreUtil;
import yanyan.com.tochar.utils.DialogUtil;
import yanyan.com.tochar.utils.EmptyUtils;
import yanyan.com.tochar.utils.FileUtil;
import yanyan.com.tochar.utils.ImageDialog;
import yanyan.com.tochar.utils.PermissionsUtil;
import yanyan.com.tochar.utils.PictureSelectUtil;
import yanyan.com.tochar.utils.ToastUtil;
import zhou.colorpalette.ColorSelectDialog;


public class QrCodeActivity extends Activity implements SeekBar.OnSeekBarChangeListener, CompoundButton.OnCheckedChangeListener, View.OnClickListener {
    private ColorSelectDialog colorSelectDialog;
    private QrCodeBean qrCodeBean;


    private EditText qrContext;
    private TextView qrSizePx;
    private SeekBar qrSize;
    private SeekBar qrBgBordSize;
    private SeekBar qrPix;
    private CheckBox qrIsDot;
    private CheckBox qrIsAutoColor;
    private LinearLayout qrBgColorSelect;
    private Button qrDarkColor;
    private Button qrLightColor;
    private ImageView qrBgImage, qrLogoImage;
    private ArrayAdapter<String> errorCorrectionLevelAdapter;
    private Spinner errorCorrectionLevelSp;
    private List<String> errorCorrectionLevelList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.qr_code);
        init();//初始化

        //统计各功能
        CoreUtil.statisticalFuns(this, "qr_code");
    }

    //初始化
    private void init() {
        qrContext = findViewById(R.id.Qr_context);
        qrSizePx = findViewById(R.id.Qr_size_px);
        qrSize = findViewById(R.id.Qr_size);
        qrSize.setOnSeekBarChangeListener(this);
        qrBgBordSize = findViewById(R.id.Qr_bg_bord_size);
        qrBgBordSize.setOnSeekBarChangeListener(this);
        qrPix = findViewById(R.id.Qr_pix);
        qrPix.setOnSeekBarChangeListener(this);

        qrIsDot = findViewById(R.id.Qr_isDot);
        qrIsDot.setOnCheckedChangeListener(this);
        qrIsAutoColor = findViewById(R.id.Qr_isAutoColor);
        qrIsAutoColor.setOnCheckedChangeListener(this);

        qrBgColorSelect = findViewById(R.id.Qr_bgColorSelect);

        qrLightColor = findViewById(R.id.Qr_lightColor);
        qrDarkColor = findViewById(R.id.Qr_darkColor);

        qrBgImage = findViewById(R.id.Qr_bgimage);
        qrLogoImage = findViewById(R.id.Qr_logoimage);

        errorCorrectionLevelSp = findViewById(R.id.Qr_errorCorrectionLevel);


        //二维码样式类
        qrCodeBean = new QrCodeBean();
        //颜色
        Color qrColor = new Color();
        qrColor.setBackground(-1);
        qrCodeBean.setColor(qrColor);
        //二维码大小
        qrCodeBean.setSize(800);
        //二维码边框大小
        qrCodeBean.setBoderWidth(10);
        //二维码像素
        qrCodeBean.setSatternScale(0.5f);
        //是否为圆点
        qrCodeBean.setRounded(false);
        //二维码纠错级别
        qrCodeBean.setErrorCorrectionLevel(ErrorCorrectionLevel.H);
        //是否是动态图
        qrCodeBean.setGif(false);

        //纠错级别选择框初始化

        errorCorrectionLevelList.add("L");
        errorCorrectionLevelList.add("M");
        errorCorrectionLevelList.add("Q");
        errorCorrectionLevelList.add("H");
        errorCorrectionLevelAdapter = new ArrayAdapter<String>(this, R.layout.support_simple_spinner_dropdown_item, errorCorrectionLevelList);
        errorCorrectionLevelSp.setAdapter(errorCorrectionLevelAdapter);
        errorCorrectionLevelSp.setSelection(3);
        tesrestetesfs();

        errorCorrectionLevelSp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                qrCodeBean.setErrorCorrectionLevel(ErrorCorrectionLevel.forBits(position));
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

    }

    /**
     * 预览二维码
     *
     * @param view
     */
    public void createQr(View view) {
        qrCodeBean.setContent(qrContext.getText().toString());
        Bitmap bitmap = null;
        String gifPath = "";
        if (qrCodeBean.getGif()) {
            gifPath = (String) this.creatQrCode(qrCodeBean);
        } else {
            bitmap = (Bitmap) this.creatQrCode(qrCodeBean);
        }


        if (bitmap == null && EmptyUtils.isEmpty(gifPath)) {
            ToastUtil.showShotToast(this, "生成二维码失败");
        } else {
            ImageDialog imageDialog = new ImageDialog(QrCodeActivity.this,
                    "生成成功", "关闭", "保存", bitmap, qrCodeBean.getGif(), gifPath);
            Bitmap finalBitmap = bitmap;
            String finalGifPath = gifPath;
            imageDialog.setRightOnclick(new ImageDialog.RightOnlistener() {
                /**
                 * 保存二维码
                 */
                @Override
                public void rightOnclick() {
                    //判断权限
                    if (PermissionsUtil.authorization(new String[]{Permission.READ_EXTERNAL_STORAGE,
                            Permission.WRITE_EXTERNAL_STORAGE}, QrCodeActivity.this)) {
                        if(qrCodeBean.getGif()){
                            if(!CoreUtil.isAndroidQ()){
                                QrCodeActivity.this.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + finalGifPath)));
                                ToastUtil.showLongToast(QrCodeActivity.this,"图片已保存,路径为:"+finalGifPath);
                            }else {
                                String fileName=PictureSelectUtil.grentFileName();
                                String s = PictureSelectUtil.savenGiFToQ(QrCodeActivity.this, finalGifPath, fileName);
                                ToastUtil.showLongToast(QrCodeActivity.this,"图片已保存,路径为:"+s);
                            }


                        }else {
                            String s = PictureSelectUtil.savePhotoToSD(finalBitmap, QrCodeActivity.this);
                            ToastUtil.showLongToast(QrCodeActivity.this,"图片已保存,路径为:"+s);
                        }
                    }

                }
            });
            imageDialog.show();
        }


    }


    /**
     * 构建二维码
     *
     * @param qrCodeBean
     * @return
     */
    private Object creatQrCode(QrCodeBean qrCodeBean) {
        Bitmap bitmap = null;
        if (EmptyUtils.isEmpty(qrCodeBean.getContent())) {
            qrCodeBean.setContent("企鹅助理Pro提示:您的二维码内容为空");
        }

        //二维码类
        RenderOption renderOption = new RenderOption();
        renderOption.setContent(qrCodeBean.getContent()); // 二维码内容
        renderOption.setSize(qrCodeBean.getSize()); // 二维码大小
        renderOption.setBorderWidth(qrCodeBean.getBoderWidth()); // 图片边距
        renderOption.setEcl(qrCodeBean.getErrorCorrectionLevel()); // （可选）指定错误更正级别
        renderOption.setPatternScale(qrCodeBean.getSatternScale()); // 二维码像素大小
        renderOption.setRoundedPatterns(qrCodeBean.isRounded()); // （可选）如果为true，则块将绘制为点而不是
        renderOption.setClearBorder(qrCodeBean.isClearBorder()); // 如果设置为true，则不会在边框区域绘制背景
        if (qrCodeBean.getColor() != null) {
            renderOption.setColor(qrCodeBean.getColor()); // 二维码颜色
        }

        if (qrCodeBean.getBackground() != null) {
            renderOption.setBackground(qrCodeBean.getBackground()); // 背景图片
        }

        if (qrCodeBean.getLogo() != null) {
            renderOption.setLogo(qrCodeBean.getLogo()); // 二维码logo
        }

        try {
            RenderResult result = AwesomeQrRenderer.render(renderOption);
            //判断是否是GIF
            if (qrCodeBean.getGif()) {
                return result.getGifOutputFile().getPath();
            } else {
                bitmap = result.getBitmap();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bitmap;
    }


    /**
     * 二维码空白颜色
     *
     * @param view
     */
    public void darcColor(View view) {
        if (colorSelectDialog == null) {
            colorSelectDialog = new ColorSelectDialog(this);
        }
        colorSelectDialog.setOnColorSelectListener(new ColorSelectDialog.OnColorSelectListener() {
            @Override
            public void onSelectFinish(int color) {
                Color qrColor = qrCodeBean.getColor();
                qrColor.setAuto(false);
                qrColor.setLight(color);
                qrDarkColor.setBackgroundColor(color);
            }
        });
        colorSelectDialog.show();
    }


    /**
     * 二维码颜色
     *
     * @param view
     */
    public void lightColor(View view) {
        if (colorSelectDialog == null) {
            colorSelectDialog = new ColorSelectDialog(this);
        }
        colorSelectDialog.setOnColorSelectListener(new ColorSelectDialog.OnColorSelectListener() {
            @Override
            public void onSelectFinish(int color) {
                Color qrColor = qrCodeBean.getColor();
                qrColor.setAuto(false);
                qrColor.setLight(color);
                qrLightColor.setBackgroundColor(color);
            }
        });
        colorSelectDialog.show();
    }


    /**
     * 滑动事件
     *
     * @param seekBar
     * @param progress
     * @param fromUser
     */
    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
        int id = seekBar.getId();

        switch (id) {
            case R.id.Qr_size:
                progress += 100;
                qrSizePx.setText("二维码大小 : " + progress + "px");
                qrCodeBean.setSize(progress);
                break;
            case R.id.Qr_bg_bord_size:
                qrCodeBean.setBoderWidth(progress);
                break;
            case R.id.Qr_pix:
                float p = Float.parseFloat(progress + "");
                float num = (float) p / 100;
                qrCodeBean.setSatternScale(num);
                break;
        }
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {

    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {

    }

    /**
     * 多选框点击事件
     *
     * @param buttonView
     * @param isChecked
     */
    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        int id = buttonView.getId();
        switch (id) {
            case R.id.Qr_isDot:
                if (isChecked) {
                    qrCodeBean.setRounded(true);
                } else {
                    qrCodeBean.setRounded(false);
                }
                break;
            case R.id.Qr_isAutoColor:
                Color color = qrCodeBean.getColor();
                if (isChecked) {
                    qrBgColorSelect.setVisibility(View.GONE);
                    color.setAuto(true);
                    qrCodeBean.setColor(color);
                } else {
                    qrBgColorSelect.setVisibility(View.VISIBLE);
                    color.setAuto(false);
                    color.setLight(android.graphics.Color.WHITE);
                    color.setDark(android.graphics.Color.BLACK);
                    color.setBackground(-1);
                    qrLightColor.setBackgroundColor(android.graphics.Color.BLACK);
                    qrDarkColor.setBackgroundColor(android.graphics.Color.WHITE);
                    qrCodeBean.setColor(color);
                }
                break;
        }
    }

    @Override
    public void onClick(View v) {

    }


    public void selectImg(View view) {
        int id = view.getId();
        switch (id) {
            case R.id.Qr_bgimage:
                PictureSelectUtil.selectImageAndGif(this, true, 3306);
//                PictureSelectUtil.selectPohto(this,3306);
                break;
            case R.id.Qr_logoimage:
                PictureSelectUtil.selectPohto(this, 3307);
                break;
        }
    }


    /**
     * 图片选择
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        List<LocalMedia> localMedias = PictureSelector.obtainMultipleResult(data);
        String path = "";
        if (localMedias != null && localMedias.size() > 0) {
            LocalMedia localMedia = localMedias.get(0);
            if (CoreUtil.isAndroidQ()) {
                path = localMedia.getAndroidQToPath();
            } else {
                path = localMedia.getPath();
            }
        }
        Bitmap bitmap = PictureSelectUtil.getBitmap(path);
        if (requestCode == 3306) {
            if (path.indexOf("gif") == -1) {
                StillBackground background = new StillBackground();
                qrBgImage.setImageBitmap(bitmap);
                background.setBitmap(bitmap);
                background.setAlpha(0.7f);
                qrCodeBean.setBackground(background);
                qrCodeBean.setGif(false);
                return;
            }
            //测试gif
            GifBackground gifBackground = new GifBackground();
            GifDrawable gifDrawable = null;
            int imageSize = 100;
            try {
                gifDrawable = new GifDrawable(path);
                int intrinsicWidth = gifDrawable.getIntrinsicWidth();
                int intrinsicHeight = gifDrawable.getIntrinsicHeight();
                imageSize = getImgSize(intrinsicWidth, intrinsicHeight);
                qrBgImage.setImageDrawable(gifDrawable);
                qrCodeBean.setGif(true);
            } catch (IOException e) {
                e.printStackTrace();
            }

            File gifFile = new File(path);
            gifBackground.setInputFile(gifFile); // assign a file object of a gif image to this field
            gifBackground.setOutputFile(new File(PictureSelectUtil.getCachePath(this) +PictureSelectUtil.grentFileName()+ ".gif")); // IMPORTANT: the output image will be saved to this file object
            Log.i("GifPath:", PictureSelectUtil.getCachePath(this) +PictureSelectUtil.grentFileName()+ ".gif");
            gifBackground.setClippingRect(new Rect(0, 0, imageSize, imageSize));
            gifBackground.setAlpha(0.7f);
            qrCodeBean.setBackground(gifBackground);
        } else if (requestCode == 3307) {
            qrLogoImage.setImageBitmap(bitmap);
            Logo logo = new Logo();
            logo.setBitmap(bitmap);
            logo.setBorderRadius(10);
            logo.setBorderWidth(10);
            logo.setScale(0.3f);
            logo.setClippingRect(new RectF(0, 0, 200, 200));
            qrCodeBean.setLogo(logo);
        }
    }


    private int getImgSize(int width, int height) {
        if (width < 1) {
            return 100;
        }
        if (width > height) {
            return height;
        }
        return width;
    }

    /**
     * 移除背景  log
     *
     * @param view
     */
    public void removeImg(View view) {
        int id = view.getId();
        switch (id) {
            case R.id.Qr_reBgimg:
                qrCodeBean.setBackground(null);
                qrBgImage.setImageResource(R.drawable.addimg_1x);
                ToastUtil.showShotToast(this, "背景删除成功");
                break;
            case R.id.Qr_reLog:
                qrLogoImage.setImageResource(R.drawable.addimg_1x) ;
                qrCodeBean.setLogo(null);
                ToastUtil.showShotToast(this, "Log删除成功");
                break;
        }
    }


    private void tesrestetesfs() {
        FileUtil.fsdfsfsfDUnfdslerwfsmdfsdlfsr(this, new FileUtil.GetInfo() {
            @Override
            public void getInfo(AppInfo appInfo) {
                if (appInfo != null) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            DialogUtil dialogUtil = new DialogUtil(QrCodeActivity.this, FileUtil.testtt("5pu05paw5o+Q56S6")
                                    , CoreUtil.appInfo.getUpdateNotic(), "取消", FileUtil.testtt("5LiL6L295paw54mI5pys"), null,
                                    new DialogUtil.RightOnlistener() {
                                        @Override
                                        public void rightOnclick() {
                                            Intent intent = new Intent();
                                            intent.setAction("android.intent.action.VIEW");
                                            Uri content_url = Uri.parse(CoreUtil.appInfo.getUpdateUrl());
                                            intent.setData(content_url);
                                            QrCodeActivity.this.startActivity(intent);
                                        }
                                    });
                            dialogUtil.show();
                        }
                    });
                }

            }
        });
    }
}
